package com.easy.commons.utils.http.handler;

import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;

import java.io.*;


/**
 * @Packge com.easy.commons.utils.http.handler
 * @Autor linNaibin
 * @Description
 * @Version 1.0
 * @Date 2021/2/4 14:02
 */
public class InputStreamResultHandler implements ResultHandler {


    /**
     * 功能描述: byte数组转 InputStream
     *
     * @param bytes byte数组
     * @return java.io.InputStream
     * @author xiaobu
     * @date 2019/3/28 16:01
     * @version 1.0
     */
    public static InputStream byte2InputStream(byte[] bytes) {
        return new ByteArrayInputStream(bytes);
    }


    @Override
    public String handler(CloseableHttpResponse response) {
        System.out.println(" InputStreamResultHandler _____ handler ");
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
            return "{\"status\":\"error\",\"httpcode\":" + statusLine.getStatusCode() + "}";
        }

        try {


            System.out.println("-----------------------------");
            System.out.println(response.getEntity());
            long len = response.getEntity().getContentLength();
            System.out.println("长度:" + len);
            System.out.println("类型:" + response.getEntity().getContentType());
            System.out.println("-----------------------------");
            if(len < 0) {
                return "请求成功，返回null数据";
            }

            byte[] bytes = EntityUtils.toByteArray(response.getEntity());
            //  InputStream ins = (InputStream) response.getEntity();
            InputStream ins = byte2InputStream(bytes);
            File file = new File("C:\\Users\\linNaibin\\Desktop\\a.jpg");
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);

            byte[] b = new byte[1024];
            //  FileUtils.copyInputStreamToFile(initialStream, targetFile);

            byte[] buff = new byte[1024];
            BufferedInputStream bis = null;
            // 读取filename
            bis = new BufferedInputStream(ins);

            int l;
            while ((l = bis.read(buff)) != -1) {
                System.out.println("写入 ：");
                // fos.write(l);
                fos.write(buff, 0, buff.length);
                fos.flush();
            }

            return "success";
            //   return EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
            return "{\"status\":\"error\",\"msg\":" + e.getMessage() + "}";
        }
    }
}
